package cn.jluzh.blog.modules.log.controller;

import cn.jluzh.blog.commons.entity.CommonEntity;
import cn.jluzh.blog.commons.result.Result;
import cn.jluzh.blog.commons.result.ResultCode;
import cn.jluzh.blog.commons.result.ResultFactory;
import cn.jluzh.blog.modules.log.aspect.annotation.AutoLog;
import cn.jluzh.blog.modules.log.eneity.SysLog;
import cn.jluzh.blog.modules.log.service.impl.LogServiceImpl;
import cn.jluzh.blog.modules.security.eneity.SecurityUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * @author hzhii
 */
@RestController
@Api(tags = "日志相关接口")
@RequestMapping("log")
public class LogController {

    @Autowired
    LogServiceImpl logService;

    @GetMapping("userLog")
    @ApiOperation("获取用户操作日志")
    public Result getAllUser(
            @RequestHeader("Oauth-Token")String token,
            @RequestParam(name="pageNum", defaultValue="1") Integer pageNum,
            @RequestParam(name="pageSize", defaultValue="5") Integer pageSize
    ){
        PageInfo<SysLog> userLog = logService.getUserLog(pageNum, pageSize, SecurityUser.getUser().getAccount());
        if(userLog!=null){
            return ResultFactory.buildResult(ResultCode.SUCCESS,"查询成功!",userLog);
        }
        else{
            return ResultFactory.buildFailResult("暂无操作记录");
        }
    }

    @GetMapping("systemLog")
    @ApiOperation("获取系统日志")
    public Result getSystemLog(
            @RequestHeader("Oauth-Token")String token,
            @RequestParam(name="pageNum", defaultValue="1") Integer pageNum,
            @RequestParam(name="pageSize", defaultValue="5") Integer pageSize
    ){
        PageHelper.startPage(pageNum, pageSize);
        List<SysLog> list = logService.list(null);
        if(list!=null){
            PageInfo<SysLog> pageInfo = new PageInfo<>(list);
            return ResultFactory.buildResult(ResultCode.SUCCESS,"查询成功!",pageInfo);
        }
        else{
            return ResultFactory.buildResult(ResultCode.SUCCESS,"暂无操作记录",null);
        }
    }

    @PostMapping("delete")
    @ApiOperation("删除系统日志")
    @AutoLog("删除系统日志")
    public Result deleteSysLog(
            @RequestHeader("Oauth-Token")String token,
            @RequestBody CommonEntity commonEntity
    ){
        logService.removeByIds(Arrays.asList(commonEntity.getIds()));
        return ResultFactory.buildSuccessResult(null);
    }

}
